<template>
  <div class="divBox">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-steps :active="$route.query.id ? currentTab - 1 : currentTab" align-center finish-status="success">
          <el-step v-if="!$route.query.id" title="选择秒杀商品" />
          <el-step title="填写基础信息" />
          <el-step title="修改商品详情" />
        </el-steps>
      </div>
      <el-form
        ref="formValidate"
        v-loading="fullscreenLoading"
        class="formValidate mt20"
        :rules="ruleValidate"
        :model="formValidate"
        label-width="150px"
        @submit.native.prevent
      >
        <!-- 秒杀商品-->
        <div v-show="!$route.query.id && currentTab === 0">
          <el-form-item label="选择商品：" prop="image">
            <div class="upLoadPicBox" @click="changeGood">
              <div v-if="formValidate.image" class="pictrue"><img :src="formValidate.image"></div>
              <div v-else class="upLoad">
                <i class="el-icon-camera cameraIconfont"/>
              </div>
            </div>
          </el-form-item>
        </div>
        <!-- 商品信息-->
        <div v-show="currentTab === 1" class="basic-info-section">
          <el-row :gutter="24">
            <el-col :span="24">
              <el-form-item label="商品主图：" prop="image" class="main-image-spacing">
                <ImageUpload v-model="formValidate.image" :limit="1" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="商品轮播图：" prop="images" class="form-item-spacing">
                <ImageUpload v-model="formValidate.images" :limit="10" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="商品标题：" prop="title" class="form-item-spacing">
                <el-input v-model="formValidate.title" maxlength="249" placeholder="请输入商品名称" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="秒杀活动简介：" class="form-item-spacing">
                <el-input v-model="formValidate.info" type="textarea" maxlength="250"  :rows="3" placeholder="请输入商品简介" />
              </el-form-item>
            </el-col>
            <!--<el-col v-bind="grid2">-->
              <!--<el-form-item label="商品分类：" prop="cateIds">-->
                <!--<el-cascader v-model="formValidate.cateIds" :options="merCateList" :props="props2" clearable class="selWidth" :show-all-levels="false" />-->
              <!--</el-form-item>-->
            <!--</el-col>-->
            <el-col v-bind="grid2">
              <el-form-item label="单位：" prop="unitName" class="form-item-spacing">
                <el-input v-model="formValidate.unitName" placeholder="请输入单位" class="selWidth"/>
              </el-form-item>
            </el-col>
            <el-col v-bind="grid2">
              <el-form-item label="运费模板：" prop="selectedShippingTemplate" class="form-item-spacing">
                <el-select v-model="selectedShippingTemplate" placeholder="请选择运费模板">
                  <el-option
                    v-for="item in shippingTemplates"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-bind="grid2">
              <el-form-item label="当天参与活动次数：" prop="num" class="form-item-spacing">
                <el-input-number v-model="formValidate.num" :step="1" step-strictly :min="1" placeholder="请输入活动次数" class="selWidth"/>
              </el-form-item>
            </el-col>
            <el-col v-bind="grid2">
              <el-form-item label="活动日期：" prop="timeVal" class="form-item-spacing">
                <el-date-picker
                  class="selWidth"
                  v-model="formValidate.timeVal"
                  value-format="yyyy-MM-dd"
                  format="yyyy-MM-dd"
                  size="small"
                  type="daterange"
                  placement="bottom-end"
                  :picker-options="pickerOptions"
                  placeholder="请选择活动日期"
                  @change="onchangeTime"
                />
              </el-form-item>
            </el-col>
            <el-col v-bind="grid2">
              <el-form-item label="活动时间：" prop="timeId" class="form-item-spacing">
                <el-select v-model="formValidate.timeId" placeholder="请选择" class="selWidth">
                  <el-option
                    v-for="item in seckillTime"
                    :key="item.id"
                    :label="item.name + ' | ' + item.time"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="活动状态：" required class="form-item-spacing">
                <el-radio-group v-model="formValidate.status">
                  <el-radio :label="0" class="radio">关闭</el-radio>
                  <el-radio :label="1">开启</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <!-- 规格表格-->
            <el-col :span="24">
              <el-form-item label="商品属性：" class="labeltop form-item-spacing" required>
                <el-table
                  ref="multipleTable"
                  :data="ManyAttrValue"
                  tooltip-effect="dark"
                  style="width: 100%"
                  @selection-change="handleSelectionChange">
                  <!-- 多规格：动态规格属性列（根据attrValue的key渲染） -->
                  <template v-if="formValidate.specType">
                    <!-- 多选按钮列 -->
                    <el-table-column type="selection" width="55" />
                    <el-table-column
                      v-for="attrKey in specAttrKeys"
                      :key="attrKey"
                      :label="attrKey"
                      align="center"
                      min-width="100">
                      <template slot-scope="scope">
                        <span class="priceBox">{{ scope.row.attrValue ? scope.row.attrValue[attrKey] : '' }}</span>
                      </template>
                    </el-table-column>
                  </template>
                  <!-- 图片列 -->
                  <el-table-column align="center" label="图片" min-width="80">
                    <template slot-scope="scope">
                      <ImageUploadAttrValue v-model="scope.row.imageArr" :limit="1" @input="val => handleAttrImageInput(scope.row, val)" />
                    </template>
                  </el-table-column>
                  <!-- 固定属性列 -->
                  <el-table-column
                    v-for="(item, key) in formThead"
                    :key="key"
                    :label="item.title"
                    align="center"
                    min-width="160">
                    <template slot-scope="scope">
                      <el-input-number
                        size="small"
                        v-if="item.title === '秒杀价'"
                        v-model="scope.row[key]"
                        :min="0"
                        :precision="2" :step="0.1"
                        class="priceBox"
                      />
                      <el-input-number
                        size="small"
                        v-else-if="item.title === '限量'"
                        v-model="scope.row[key]"
                        type="number"
                        :min="1"
                        :max="scope.row.stock"
                        :step="1" step-strictly
                        class="priceBox"
                      />
                      <span v-else class="priceBox">{{ scope.row[key] }}</span>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <!-- 商品详情-->
        <div v-show="currentTab === 2">
          <el-form-item label="商品详情：">
            <tinymce v-model="formValidate.content" :height="400" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSubmit">提交</el-button>
            <el-button @click="handleSubmitUp">上一步</el-button>
          </el-form-item>
        </div>
        <el-form-item style="margin-top:30px;">
          <el-button
            v-show="(!$route.query.id && currentTab > 0) || ($route.query.id && currentTab > 1)"
            type="primary"
            class="submission"
            size="small"
            @click="handleSubmitUp"
          >上一步</el-button>
          <el-button
            v-show="!$route.query.id && currentTab == 0"
            type="primary"
            class="submission"
            size="small"
            @click="handleSubmitNest1()"
          >下一步</el-button>
          <el-button
            v-show="currentTab == 1"
            type="primary"
            class="submission"
            size="small"
            @click="handleSubmitNest2('formValidate')"
          >下一步</el-button>
          <el-button
            v-show="currentTab===2"
            :loading="loading"
            type="primary"
            class="submission"
            size="small"
            @click="handleSubmit('formValidate')"
            v-hasPermi="['admin:seckill:update']"
          >提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 商品选择弹窗 -->
    <ProductSelectDialog ref="productSelectDialog" @confirm="handleProductSelect" />
  </div>
</template>

<script>
  import ImageUpload from '@/components/ImageUpload';
  import ImageUploadAttrValue from '@/components/ImageUploadAttrValue';
  import * as StoreSeckillApi from '@/api/marketing/storeseckill';
  import * as StoreSeckillMangerApi from '@/api/marketing/storeseckillmanger';
  import ProductSelectDialog from './ProductSelectDialog.vue'
  const defaultObj = {
    image: '',
    images: [],
    title: '',
    info: '',
    num: 1,
    unitName: '',
    sort: 0,
    giveIntegral: 0,
    ficti: 0,
    status: 0,
    tempId: '',
    productId: 0,
    attrValue: [{
      image: '',
      price: 0,
      cost: 0,
      otPrice: 0,
      stock: 0,
      quota: 0,
      barCode: '',
      weight: 0,
      volume: 0,
    }],
    attr: [],
    selectRule: '',
    content: '',
    specType: false,
    id: 0,
    timeId: null,
    startTime: '',
    stopTime: '',
    timeVal: [],
  }
  const objTitle = {
    price: {
      title: '秒杀价'
    },
    cost: {
      title: '成本价'
    },
    otPrice: {
      title: '原价'
    },
    stock: {
      title: '库存'
    },
    quota: {
      title: "限量",
    },
    barCode: {
      title: '商品编号'
    },
    weight: {
      title: '重量（KG）'
    },
    volume: {
      title: '体积(m³)'
    }
  }
  export default {
    name: "creatSeckill",
    components: { ProductSelectDialog, ImageUpload, ImageUploadAttrValue },
    data() {
      return {
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() < new Date().setTime(new Date().getTime() - 3600 * 1000 * 24);
          }
        },
        props2: {
          children: 'child',
          label: 'name',
          value: 'id',
          multiple: true,
          emitPath: false
        },
        grid2: {
          xl: 8,
          lg: 10,
          md: 12,
          sm: 24,
          xs: 24
        },
        currentTab: 0,
        formThead: Object.assign({}, objTitle),
        formValidate: Object.assign({}, defaultObj),
        loading: false,
        fullscreenLoading: false,
        merCateList: [], // 商户分类筛选
        shippingList: [], // 运费模板
        seckillTime: [],
        ruleValidate: {
          productId: [
            { 
              required: !this.$route.query.id, // 编辑模式下不强制要求选择商品
              message: '请选择商品', 
              trigger: 'change' 
            }
          ],
          title: [
            { required: true, message: '请输入商品标题', trigger: 'blur' }
          ],
          attrValue: [
            { required: true, message: '请选择商品属相', trigger: 'change', type: 'array', min: '1' }
          ],
          num: [
            { required: true, message: '请输入活动次数', trigger: 'blur' }
          ],
          unitName: [
            { required: true, message: '请输入单位', trigger: 'blur' }
          ],
          info: [
            { required: true, message: '请输入秒杀商品简介', trigger: 'blur' }
          ],
          tempId: [
            { required: true, message: '请选择运费模板', trigger: 'change' }
          ],
          timeId: [
            { required: true, message: '请选择活动时间', trigger: 'change' }
          ],
          image: [
            { required: true, message: '请上传商品图', trigger: 'change' }
          ],
          images: [
            { required: true, message: '请上传商品轮播图', type: 'array', trigger: 'change' }
          ],
          specType: [
            { required: true, message: '请选择商品规格', trigger: 'change' }
          ],
          timeVal:[
            { required: true, message: '请选择活动日期', trigger: 'change', type: 'array'}
          ]
        },
        manyTabDate: {},
        manyTabTit: {},
        attrInfo: {},
        tempRoute: {},
        multipleSelection: [],
        productId: 0,
        OneattrValue: [Object.assign({}, defaultObj.attrValue[0])], // 单规格
        ManyAttrValue: [Object.assign({}, defaultObj.attrValue[0])], // 多规格
        showColorColumn: false,
        uploadFileList: [], // 轮播图el-upload file-list
        mainImageFileList: [], // 主图el-upload file-list
        shippingTemplates: [
          { id: 0, name: '全国包邮' },
          { id: 1, name: '不包邮' }
        ],
        selectedShippingTemplate: null,
        selectedProduct: null,
      }
    },
    computed: {
      // 多规格时，返回所有规格属性名（根据ManyAttrValue中所有attrValue的key去重合并）
      specAttrKeys() {
        if (!this.formValidate.specType || !this.ManyAttrValue || this.ManyAttrValue.length === 0) return [];
        const keys = new Set();
        this.ManyAttrValue.forEach(item => {
          if (item.attrValue && typeof item.attrValue === 'object') {
            Object.keys(item.attrValue).forEach(k => keys.add(k));
          }
        });
        return Array.from(keys);
      },
      attrValue() {
        const obj = Object.assign({}, defaultObj.attrValue[0])
        delete obj.image
        return obj
      }
    },
    created() {
      this.$watch('formValidate.attr', this.watCh)
      this.tempRoute = Object.assign({}, this.$route)
    },
    mounted() {
      // 获取秒杀时间段列表
      StoreSeckillMangerApi.getStoreSeckillMangerPage({
        pageNo: 1,
        pageSize: 10,
        status: 1
      }).then((res) => {
        if (res.code === 0) {
          this.seckillTime = res.data.list.map(item => ({
            id: item.id,
            name: item.name,
            time: `${item.startTime}:00 - ${item.endTime}:00`
          }));
        }
      });
      this.formValidate.images = [];
      if ( this.$route.query.id ) {
        this.setTagsViewTitle()
        this.getInfo()
        // 编辑模式下跳过选择商品阶段，直接到填写基础信息阶段
        this.currentTab = 1
      }
      this.getShippingList()
      this.getCategorySelect()
      this.initUploadFileList()
      
      // 在表格渲染完成后，根据isChecked设置选中状态
      this.$nextTick(() => {
        this.setInitialSelection();
      });
      this.ManyAttrValue.forEach(row => {
        row.imageArr = row.image ? [row.image] : [];
      });
    },
    methods: {
      // 添加新方法：设置初始选中状态
      setInitialSelection() {
        if (this.$refs.multipleTable && this.ManyAttrValue) {
          this.ManyAttrValue.forEach((row, index) => {
            if (row.isChecked) {
              this.$refs.multipleTable.toggleRowSelection(row, true);
            }
          });
        }
      },
      watCh(val) {
        const tmp = {}
        const tmpTab = {}
        this.formValidate.attr.forEach((o, i) => {
          // tmp['value' + i] = { title: o.attrName }
          // tmpTab['value' + i] = ''
          tmp[o.attrName] = { title: o.attrName };
          tmpTab[o.attrName] = '';
        })
        this.manyTabTit = tmp
        this.manyTabDate = tmpTab
        this.formThead = Object.assign({}, this.formThead, tmp)
      },
      handleRemove (i) {
        this.formValidate.images.splice(i, 1)
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
        // 更新ManyAttrValue中的isChecked状态
        this.ManyAttrValue.forEach(item => {
          const wasChecked = item.isChecked;
          item.isChecked = val.some(selected => selected === item);
          
          // 当选中isChecked为false的商品属性时，将该商品属性的productId修改成当前秒杀商品的id
          if (!wasChecked && item.isChecked) {
            // 获取当前秒杀商品的ID
            const currentSeckillId = this.$route.query.id || this.formValidate.id;
            if (currentSeckillId) {
              // 编辑模式下，直接设置productId
              item.productId = currentSeckillId;
            } else {
              // 新增模式下，标记需要更新productId，在提交时处理
              item.needUpdateProductId = true;
            }
          }
        });
      },
      // 点击商品图
      modalPicTap (tit, num, i) {
        const _this = this
        this.$modalUpload(function(img) {
          if(tit==='1'&& !num){
            _this.formValidate.image = img[0].sattDir
            _this.ManyAttrValue[0].image = img[0].sattDir
          }
          if(tit==='2'&& !num){
            if(img.length>10) return this.$message.warning("最多选择10张图片！");
            if(img.length + _this.formValidate.images.length > 10) return this.$message.warning("最多选择10张图片！");
            img.map((item) => {
              _this.formValidate.images.push(item.sattDir)
            });
          }
          if(tit==='1'&& num === 'duo' ){
            _this.ManyAttrValue[i].image = img[0].sattDir
          }
        },tit, 'content')
      },
      // 具体日期
      onchangeTime(e) {
        this.formValidate.timeVal = e;
        this.formValidate.startTime = e ? e[0] : "";
        this.formValidate.stopTime = e ? e[1] : "";
      },
      changeGood(){
        // 打开商品选择弹窗
        this.$refs.productSelectDialog.open();
      },
      // 处理商品选择
      handleProductSelect(selectedProducts) {
        if (selectedProducts && selectedProducts.length > 0) {
          const product = selectedProducts[0];
          // 输出选中商品信息到控制台
          console.log('选中商品信息:', product);
          this.selectedProduct = product;
          this.formValidate.image = product.image;
          let imgs = [];
          if (product.sliderImage && Array.isArray(product.sliderImage)) {
            imgs = product.sliderImage;
          } else if (product.images) {
            imgs = Array.isArray(product.images) ? product.images : [];
          } else {
            imgs = [product.image];
          }
          this.formValidate.images = imgs;

          // 同步商品其它信息到formValidate
          this.formValidate.title = product.storeName || product.name || '';
          // 优先用product.info，其次storeInfo，再次description，最后空
          this.formValidate.info = product.storeInfo || '';
          this.formValidate.unitName = product.unitName || '';
          this.formValidate.price = product.price || 0;
          this.formValidate.cost = product.cost || 0;
          this.formValidate.otPrice = product.otPrice || 0;
          this.formValidate.stock = product.stock || 0;
          this.formValidate.sort = product.sort || 0;
          this.formValidate.postage = product.postage || 0;
          this.formValidate.productId = product.id;
          this.formValidate.specType = product.specType !== undefined ? product.specType : false;

          this.initUploadFileList();
          this.$message.success(`已选择商品：${product.storeName || product.name || '未知商品'}`);
          this.selectedShippingTemplate = product.isPostage === 0 ? 0 : 1;

          // 获取商品属性并初始化ManyAttrValue
          StoreSeckillApi.getProductAttrValue(null, product.id).then(attrRes => {
            if (attrRes.code === 0 && Array.isArray(attrRes.data) && attrRes.data.length > 0) {
              const processedData = attrRes.data.map(item => {
                const attrValue = JSON.parse(item.attr_value || '{}');
                return {
                  ...item,
                  ...attrValue,
                  isChecked: item.isChecked || item.ischecked || false,
                  imageArr: item.image ? [item.image] : []
                }
              });
              this.formValidate.attr = this.generateAttrFromData(processedData);
              this.formValidate.attrValue = processedData;
              this.ManyAttrValue = processedData;
            } else {
              // 没有属性时，初始化一个默认属性结构
              const defaultAttr = [{
                image: product.image || '',
                price: product.price || 0,
                cost: product.cost || 0,
                otPrice: product.otPrice || 0,
                stock: product.stock || 0,
                quota: 0,
                barCode: '',
                weight: 0,
                volume: 0,
                imageArr: product.image ? [product.image] : []
              }];
              this.formValidate.attrValue = defaultAttr;
              this.ManyAttrValue = defaultAttr;
            }
          });
        }
      },
      handleSubmitNest1() {
        if (!this.formValidate.image) {
          return this.$message.warning("请选择商品！");
        } else {
          this.currentTab++;
          // 移除商品查询逻辑，商品信息已在选择商品弹窗中获取
        }
      },
      // 商品分类；
      getCategorySelect() {
        // 暂时注释掉，因为没有对应的API
        // categoryApi({ status: -1, type: 1 }).then(res => {
        //   this.merCateList = this.filerMerCateList(res)
        // })
      },
      filerMerCateList(treeData) {
        return treeData.map((item) => {
          if(!item.child){
            item.disabled = true
          }
          item.label = item.name
          return item
        })
      },
      // 运费模板；
      getShippingList() {
        // 暂时注释掉，因为没有对应的API
        // shippingTemplatesList(this.tempData).then(res => {
        //   this.shippingList = res.list
        // })
      },
      // 运费模板
      addTem() {
        // 暂时注释掉，因为没有对应的组件
        // this.$refs.addTemplates.dialogVisible = true
        // this.$refs.addTemplates.getCityList()
      },
      // 商品详情
      async getInfo () {
        if(this.$route.query.id){
          await this.getSekllProdect(this.$route.query.id)
        }
        this.initUploadFileList();
      },
      getProdect(id) {
        this.fullscreenLoading = true
        this.fullscreenLoading = false
      },
      async getSekllProdect(id) {
        this.fullscreenLoading = true
        try {
          // 1. 获取秒杀商品详情
          const seckillRes = await StoreSeckillApi.getStoreSeckill(id);
          if (!seckillRes.data) {
            this.$message.error('获取秒杀商品详情失败');
            this.fullscreenLoading = false;
            return;
          }
          let info = seckillRes.data;

          // 数据字段映射，确保字段名称匹配
          const mappedData = {
            id: info.id,
            image: info.image,
            sliderImage: info.sliderImage || info.images,
            title: info.title,
            info: info.info,
            quota: info.quota,
            unitName: info.unitName,
            sort: info.sort || 0,
            status: info.status,
            tempId: info.tempId,
            attr: info.attr || [],
            attrValue: info.attrValue || [],
            selectRule: info.selectRule,
            content: info.content,
            specType: info.specType !== undefined ? info.specType : false,
            productId: info.productId,
            giveIntegral: info.giveIntegral || 0,
            ficti: info.ficti || 0,
            timeId: info.timeId,
            startTime: info.startTimeStr || info.startTime,
            stopTime: info.stopTimeStr || info.stopTime,
            num: info.num || 1,
            price: info.price,
            cost: info.cost,
            otPrice: info.otPrice,
            stock: info.stock,
            postage: info.postage || 0,
            isPostage: info.isPostage
          };

          // 处理图片URL和轮播图
          const processImageUrl = (url) => {
            if (!url) return '';
            if (this.$selfUtil && this.$selfUtil.setDomain) {
              return this.$selfUtil.setDomain(url);
            }
            return url;
          };
          let sliderImages = [];
          try {
            if (mappedData.sliderImage) {
              sliderImages = JSON.parse(mappedData.sliderImage);
            }
          } catch (e) {
            console.error('解析轮播图数据失败:', e);
            sliderImages = [];
          }

          // 填充表单
          this.formValidate = {
            image: processImageUrl(mappedData.image),
            images: sliderImages,
            title: mappedData.title,
            info: mappedData.info,
            quota: mappedData.quota,
            unitName: mappedData.unitName,
            sort: mappedData.sort,
            status: mappedData.status,
            tempId: mappedData.tempId,
            attr: mappedData.attr,
            attrValue: mappedData.attrValue,
            selectRule: mappedData.selectRule,
            content: mappedData.content,
            specType: mappedData.specType !== undefined ? mappedData.specType : false,
            productId: mappedData.productId,
            giveIntegral: mappedData.giveIntegral,
            ficti: mappedData.ficti,
            timeId: mappedData.timeId,
            startTime: mappedData.startTime,
            stopTime: mappedData.stopTime,
            num: mappedData.num,
            timeVal: (mappedData.startTime && mappedData.stopTime) ? [mappedData.startTime.split(' ')[0], mappedData.stopTime.split(' ')[0]] : [],
            id: mappedData.id
          }

          // 填充其他数据
          this.selectedProduct = {
            id: mappedData.productId,
            image: mappedData.image,
            storeName: mappedData.title,
            storeInfo: mappedData.info,
            unitName: mappedData.unitName,
            tempId: mappedData.tempId,
            price: mappedData.price,
            cost: mappedData.cost,
            otPrice: mappedData.otPrice,
            stock: mappedData.stock,
            sort: mappedData.sort,
            postage: mappedData.postage,
            specType: mappedData.specType !== undefined ? mappedData.specType : false,
            isPostage: mappedData.isPostage
          };
          this.selectedShippingTemplate = mappedData.isPostage === 0 ? 0 : 1;
          
          // 2. 获取最新的商品属性
          if (mappedData.productId) {
            const attrRes = await StoreSeckillApi.getProductAttrValue(mappedData.id, mappedData.productId);
            if (attrRes.code === 0 && Array.isArray(attrRes.data)) {
              const processedData = JSON.parse(JSON.stringify(attrRes.data)).map(item => {
                const attrValue = JSON.parse(item.attr_value || '{}');
                return {
                ...item,
                  ...attrValue,
                  isChecked: item.isChecked || item.ischecked || false,
                  imageArr: item.image ? [item.image] : []
                }
              });
              this.formValidate.attr = this.generateAttrFromData(processedData);
              this.formValidate.attrValue = processedData;
              this.ManyAttrValue = processedData;
            } else {
              console.warn('getProductAttrValue(编辑)无数据或异常:', attrRes);
            }
          }

          // 3. 处理多规格属性，并根据 isChecked 字段勾选
          if (mappedData.specType) {
            this.$nextTick(() => {
              this.ManyAttrValue.forEach((item, index) => {
                // 使用 $set 确保新属性是响应式的
                this.$set(this.ManyAttrValue, index, {
                  ...item,
                  isChecked: item.isChecked || false
                });

                // 处理 attrValue，确保格式正确
                if (item.attrValue && typeof item.attrValue === 'string') {
                  try {
                    const parsedAttrValue = JSON.parse(item.attrValue);
                    // 不展开到顶层，保持attrValue对象
                    this.$set(this.ManyAttrValue[index], 'attrValue', parsedAttrValue);
                  } catch (e) { 
                    console.error('解析attrValue失败:', e); 
                  }
                }

                item.image = processImageUrl(item.image);

                // 根据 isChecked 字段勾选
                if (item.isChecked) {
                  this.$set(this.ManyAttrValue[index], 'price', item.price);
                  this.$set(this.ManyAttrValue[index], 'quota', item.quota);
                  this.$nextTick(() => {
                    if (this.$refs.multipleTable) {
                      this.$refs.multipleTable.toggleRowSelection(this.ManyAttrValue[index], true);
                    }
                  });
                }
              });
            });
          }

          // 4. 更新UI
          this.initUploadFileList();
          this.$forceUpdate();

        } catch (error) {
          console.error('获取秒杀商品详情失败:', error);
          this.$message.error('获取秒杀商品详情失败');
        } finally {
          this.fullscreenLoading = false;
        }
      },
      handleSubmitNest2(name) {
        // 输出images到控制台
        this.$refs[name].validate((valid) => {
          if (valid) {
            if(this.formValidate.specType && this.multipleSelection.length ===0 ) return this.$message.warning("请填选择至少一个商品属性！");
            this.currentTab++;
          } else {
            return false;
          }
        });
      },
      formatDateTime(val) {
        if (!val) return '';
        if (typeof val === 'string') return val;
        const pad = n => n < 10 ? '0' + n : n;
        return `${val.getFullYear()}-${pad(val.getMonth() + 1)}-${pad(val.getDate())} ${pad(val.getHours())}:${pad(val.getMinutes())}:${pad(val.getSeconds())}`;
      },
      async handleSubmit() {
        this.loading = true;
        try {
          // --- Data Preparation ---
          const totalQuota = this.ManyAttrValue.reduce((sum, item) => sum + (Number(item.quota) || 0), 0);
          const totalSales = this.ManyAttrValue.reduce((sum, item) => sum + (Number(item.sales) || 0), 0);
          const [start, end] = this.formValidate.timeVal || [];
          const startTime = start ? `${start} 00:00:00` : '';
          const stopTime = end ? `${end} 23:59:59` : '';

          const mainData = {
            productId: this.formValidate.productId,
            image: this.formValidate.image,
            images: JSON.stringify(this.formValidate.images),
            title: this.formValidate.title,
            info: this.formValidate.info,
            price: this.selectedProduct?.price || 0,
            cost: this.selectedProduct?.cost || 0,
            otPrice: this.selectedProduct?.otPrice || 0,
            giveIntegral: this.formValidate.giveIntegral,
            sort: this.selectedProduct?.sort || 0,
            stock: this.selectedProduct?.stock || 0,
            sales: totalSales,
            unitName: this.formValidate.unitName,
            postage: this.selectedProduct?.postage || 0,
            description: this.formValidate.content,
            startTime: startTime,
            stopTime: stopTime,
            status: this.formValidate.status,
            isPostage: this.selectedShippingTemplate === 0 ? 0 : 1,
            isDel: 0,
            num: this.formValidate.num,
            tempId: this.formValidate.tempId,
            weight: 0,
            volume: 0,
            quota: totalQuota,
            quotaShow: totalQuota,
            timeId: this.formValidate.timeId,
            specType: this.formValidate.specType,
            isShow: 1, // 默认显示
          };

          if (this.$route.query.id) {
            mainData.id = this.$route.query.id;
          }

          // --- API Call 1: Create/Update Seckill Product ---
          const res = await StoreSeckillApi[this.$route.query.id ? 'updateStoreSeckill' : 'createStoreSeckill'](mainData);

          if (res.code !== 0 && res.data !== true) {
            this.$message.error(res.msg || (this.$route.query.id ? '更新秒杀商品失败' : '创建秒杀商品失败'));
            return; // Early exit
          }

          // --- API Call 2: Create/Update Attributes (if any) ---
          if (this.ManyAttrValue && this.ManyAttrValue.length > 0) {
            const attrValues = this.ManyAttrValue.map(item => {
              // 处理attrValue：直接使用item.attrValue，如果不存在则构建一个
              let attrValueData = {};
              if (item.attrValue) {
                // 如果attrValue是字符串，尝试解析
                if (typeof item.attrValue === 'string') {
                  try {
                    attrValueData = JSON.parse(item.attrValue);
                  } catch (e) {
                    console.error('解析attrValue失败:', e);
                    attrValueData = {};
                  }
                } else if (typeof item.attrValue === 'object') {
                  attrValueData = item.attrValue;
                }
              } else {
                // 如果没有attrValue，从item中提取属性值（排除标准字段）
                const standardFields = ['image', 'price', 'cost', 'otPrice', 'stock', 'quota', 'quotaShow', 'barCode', 'weight', 'volume', 'id', 'productId', 'type', 'unique', 'suk', 'isDel', 'sales', 'isChecked', 'needUpdateProductId'];
                Object.keys(item).forEach(key => {
                  if (!standardFields.includes(key)) {
                    attrValueData[key] = item[key];
                  }
                });
              }

              // Logic for isDel: mark for deletion if it's an existing seckill attribute that's been deselected
              const isDelValue = (this.$route.query.id && item.id && !item.isChecked && item.type === 1) ? 1 : 0;

              let productId = item.productId || this.formValidate.productId;
              let type = item.type !== undefined ? item.type : 1;
              // 新增时，type强制为1，productId为res.data
              if (!this.$route.query.id) {
                productId = res.data;
                type = 1;
              } else if (item.needUpdateProductId && res.data) {
                productId = res.data;
              }

              const attrValue = {
                productId: productId,
                seckillId: this.$route.query.id || res.data,
                image: item.image || '',
                price: item.price || 0,
                cost: item.cost || 0,
                otPrice: item.otPrice || 0,
                stock: item.stock || 0,
                barCode: item.barCode || '',
                weight: item.weight || 0,
                volume: item.volume || 0,
                suk: item.suk || '',
                type: type, // 秒杀类型
                quota: item.quota || 0,
                quotaShow: item.quotaShow || 0,
                sales: item.sales || 0,
                attrValue: JSON.stringify(attrValueData),
                isDel: isDelValue,
                isChecked: item.isChecked || false
              };
              // 仅编辑时保留id，新增时不传id
              if (this.$route.query.id && item.id) {
                attrValue.id = item.id;
              }
              return attrValue;
            });

            const attrRes = await StoreSeckillApi[this.$route.query.id ? 'updateAttrValue' : 'attrValueCreate'](attrValues);

            if (attrRes.code !== 0 && attrRes.data !== true) {
              this.$message.error(attrRes.msg || '商品属性操作失败');
              return; // Early exit
            }
          }

          // --- Success ---
          this.$message.success('提交成功');
          this.$router.push('/marketing/seckill/store-seckill');

        } catch (e) {
          console.error(e);
          if (e.response && e.response.status === 409) {
            this.$message.error(e.response.data.message || '商品秒杀产品名已存在');
          } else {
            this.$message.error('提交失败，请查看控制台');
          }
        } finally {
          this.loading = false;
        }
      },
      handleSubmitUp() {
        if (this.$route.query.id) {
          // 编辑模式下，从步骤2回到步骤1
          if (this.currentTab > 1) {
            this.currentTab--;
          }
        } else {
          // 新增模式下，正常步骤切换
          if (this.currentTab-- < 0) this.currentTab = 0;
        }
      },
      setTagsViewTitle() {
        const title = '编辑秒杀商品'
        const route = Object.assign({}, this.tempRoute, { title: `${title}-${this.$route.query.id}` })
        this.$store.dispatch('tagsView/updateVisitedView', route)
      },
      // 移动
      handleDragStart (e, item) {
        this.dragging = item;
      },
      handleDragEnd (e, item) {
        this.dragging = null
      },
      handleDragOver (e) {
        e.dataTransfer.dropEffect = 'move'
      },
      handleDragEnter (e, item) {
        e.dataTransfer.effectAllowed = 'move'
        if (item === this.dragging) {
          return
        }
        const newItems = [...this.formValidate.images]
        const src = newItems.indexOf(this.dragging)
        const dst = newItems.indexOf(item)
        newItems.splice(dst, 0, ...newItems.splice(src, 1))
        this.formValidate.images = newItems;
      },
      getColorText(row) {
        if (row.颜色) {
          return row.颜色;
        } else if (row.suk) {
          return row.suk;
        } else if (row.attrValue) {
          try {
            const attrValue = typeof row.attrValue === 'string' ? JSON.parse(row.attrValue) : row.attrValue;
            return attrValue.颜色 || '';
          } catch (e) {
            return '';
          }
        }
        return '';
      },
      initUploadFileList() {
        // 主图
        this.mainImageFileList = this.formValidate.image
          ? [{ name: '主图', url: this.formValidate.image, status: 'success' }]
          : [];
        // 轮播图
        const imgs = Array.isArray(this.formValidate.images) ? this.formValidate.images : [];
        this.uploadFileList = imgs.map((url, idx) => ({
          name: `图片${idx + 1}`,
          url,
          status: 'success'
        }));
        this.formValidate.images = imgs;
      },
      // 添加商品属性图片上传处理方法
      handleAttrImageInput(row, val) {
        row.image = Array.isArray(val) && val.length > 0 ? val[0] : '';
        row.imageArr = Array.isArray(val) ? val : [];
      },
      // Add a new helper method to generate `formValidate.attr`
      generateAttrFromData(data) {
        if (!data || data.length === 0) {
            return [];
        }
        const attrKeys = new Set();
        data.forEach(item => {
            const attrValue = JSON.parse(item.attr_value || '{}');
            Object.keys(attrValue).forEach(key => attrKeys.add(key));
        });

        return Array.from(attrKeys).map(key => ({
            attrName: key,
            attrValues: [] // Values are not needed for header generation
        }));
      },
    }
  }
</script>

<style scoped lang="scss">
  // 基础信息页面美化样式
  .basic-info-section {
    padding: 20px 0;
    
    // 只针对商品主图和商品轮播图增加更大间距
    .main-image-spacing {
      margin-bottom: 40px !important;
    }
    .form-item-spacing {
      margin-bottom: 24px;
      ::v-deep .el-form-item__label {
        font-weight: 500;
        color: #333;
        line-height: 32px;
      }
      ::v-deep .el-form-item__content {
        line-height: 32px;
      }
      ::v-deep .el-input__inner {
        border-radius: 4px;
        border: 1px solid #dcdfe6;
        transition: border-color 0.2s;
        &:focus {
          border-color: #409eff;
        }
      }
      ::v-deep .el-textarea__inner {
        border-radius: 4px;
        border: 1px solid #dcdfe6;
        transition: border-color 0.2s;
        &:focus {
          border-color: #409eff;
        }
      }
      ::v-deep .el-select .el-input__inner {
        border-radius: 4px;
      }
      ::v-deep .el-date-editor {
        border-radius: 4px;
      }
      ::v-deep .el-input-number {
        border-radius: 4px;
      }
    }
    // 表格美化
    ::v-deep .el-table {
      border-radius: 8px;
      overflow: hidden;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      .el-table__header-wrapper {
        background-color: #f5f7fa;
        th {
          background-color: #f5f7fa;
          color: #333;
          font-weight: 600;
        }
      }
      .el-table__body-wrapper {
        tr:hover {
          background-color: #f5f7fa;
        }
      }
    }
  }

  // 下面保留原有样式
  .labeltop{
    ::v-deep.el-input-number--small{
      /*width: 172px !important;*/
      min-width: 132px !important;
    }
  }
  .proCoupon{
    ::v-deep.el-form-item__content{
      margin-top: 5px;
    }
  }
  .tabPic{
    width: 40px !important;
    height: 40px !important;
    img{
      width: 100%;
      height: 100%;
    }
  }
  .noLeft{
    ::v-deep.el-form-item__content{
      margin-left: 0 !important;
    }
  }
  .tabNumWidth{
    ::v-deep.el-input-number--medium{
      width: 121px !important;
    }
    ::v-deep.el-input-number__increase{
      width: 20px !important;
      font-size: 12px !important;
    }
    ::v-deep.el-input-number__decrease{
      width: 20px !important;
      font-size: 12px !important;
    }
    ::v-deep.el-input-number--medium .el-input__inner {
      padding-left: 25px !important;
      padding-right: 25px !important;
    }
    ::v-deep thead{
      line-height: normal !important;
    }
    ::v-deep .el-table .cell{
      line-height: normal !important;
    }
  }
  .selWidth{
    width: 80%;
  }
  .selWidthd{
    width: 300px;
  }
  .button-new-tag {
    height: 28px;
    line-height: 26px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
  .pictrue{
    width: 60px;
    height: 60px;
    border: 1px dotted rgba(0,0,0,0.1);
    margin-right: 10px;
    position: relative;
    cursor: pointer;
    img{
      width: 100%;
      height: 100%;
    }
  }
  .btndel{
    position: absolute;
    z-index: 1;
    width :20px !important;
    height: 20px !important;
    left: 46px;
    top: -4px;
  }
  .labeltop{
    ::v-deep.el-form-item__label{
      /*float: none !important;*/
      /*display: inline-block !important;*/
      /*margin-left: 120px !important;*/
      /*width: auto !important;*/
    }
  }
  /* 主图和轮播图上传图片缩略图尺寸 */
  .el-upload-list--picture-card .el-upload-list__item,
  .el-upload--picture-card {
    width: 100px !important;
    height: 100px !important;
  }
  .el-upload-list--picture-card .el-upload-list__item-thumbnail {
    width: 100px !important;
    height: 100px !important;
    object-fit: cover;
  }
  .el-upload--picture-card {
    line-height: 100px !important;
  }
  .attr-image-container {
    display: flex;
    align-items: center;
    gap: 8px;

    .attr-info {
      text-align: left;
      font-size: 12px;
      color: #606266;

      .attr-item {
        white-space: nowrap;
        line-height: 1.5;
      }
    }
  }
</style>

